
//
//  FileModelEntity.m
//  MultiMedia
//
//  Created by zorro on 14-12-5.
//  Copyright (c) 2014年 zorro. All rights reserved.
//

#import "FileModelEntity.h"
#import "YYJSONHelper.h"
#import "DownloadEntity.h"
#import "NSString+SBJSON.h"
#import "XYSandbox.h"
#import "AFNetworking.h"

#import "SNUserInfoModel.h"
#import "SportModel.h"
#import "SleepModel.h"
#import "HeartModel.h"
#import "OxModel.h"
#import "BpModel.h"

@implementation FileModelEntity

DEF_SINGLETON(FileModelEntity)

- (void)checkUpdateFirmwareInfo {
    if (KK_BLEModel.bleAdvID > 0 && [HASLOGIN getBOOLValue]) {
        [self fileModelRequestWithBaseLink:@"/support/hwversion2" withRequestType:FileModelEntityRequestFirmware];
    }
}

//新的接口
- (void)fileModelRequestWithBaseLink:(NSString *)link withRequestType:(FileModelEntityRequest)requestType {
    
    //    NSDictionary *dict = @{@"adv_id" : @(KK_BLEModel.bleAdvID), @"customid" : @(KK_BLEModel.bleCustomerID)};
    //
//    if (_lastAdv == KK_BLEModel.bleAdvID && _lastDeviceId == KK_BLEModel.deviceID) {
//        if (KK_ShareData.isDown) {
//            return;
//        }
//    } else {
//        KK_ShareData.isDown = NO;
//    }
    
//    if (_lastAdv == KK_BLEModel.bleAdvID && _lastCustoms ==KK_BLEModel.bleCustomerID && _lastDeviceId ==KK_BLEModel.deviceID) {
//        NSLog(@"已经存在升级固件");
//        return;
//    }
    
    NSDictionary *dict = @{@"adv_id" : @(KK_BLEModel.bleAdvID), @"customid" : @(KK_BLEModel.bleCustomerID), @"upgradeid":@(KK_BLEModel.deviceID)};
//    NSLog(@"请求升级包接口dict>>>>>>>%@ 设备升级ID>>>%d %d", dict, KK_BLEModel.deviceID, KK_BLEModel.bleVersion);
    
    HttpRequest *hr = [self.requestHelper get:link params:dict];
    [hr succeed:^(MKNetworkOperation *op)
     {
         NSString *str = [op responseString];
         //           NSLog(@"[op responseString] = ..%@", str);
         NSDictionary *dic = str.JSONValue;
         if (dic[@"ret"] && [dic[@"ret"] integerValue] == 0) {
             NSDictionary *dicN = [dic objectForKey:@"data"];
             KK_BLEModel.bleOnlineVersion = [dicN[@"version"] integerValue];
             KK_BLEModel.download_url = dicN[@"download_url"];
             KK_BLEModel.chip = [dicN[@"chip"] lowercaseString];
             NSLog(@"KK_BLEModel.bleOnlineVersion===%ld,KK_BLEModel.download_url==%@", KK_BLEModel.bleOnlineVersion, KK_BLEModel.download_url);
             [KK_BLEModel updateToDB];
  
             NSDate *now = [NSDate date];
             if (now.hour>=9 && KK_BLEModel.isConnected) {
                 NSString *time = [[NSDate date]dateToDayString];
                 NSString *key = [NSString stringWithFormat:@"%@ mac:%@",time,KK_BLEModel.bleMAC];
                 NSLog(@"🙂🙂🙂 在线版本:%d 当前版本:%d 是否连接%i",KK_BLEModel.bleOnlineVersion,KK_BLEModel.bleVersion,KK_BLEModel.isConnected);
                 if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion) {
                     BOOL isSave = [key getBOOLValue];
                     NSLog(@"🙂 有更新版本key:%@ 是否提示过:%i",key,isSave);
                     if (!isSave) {
                         [[NSNotificationCenter defaultCenter]postNotificationName:OTACANINFONOTICE object:nil];
                         _otacanInfo = YES;
                     }
                 }
             }
             
             if (KK_BLEModel.bleOnlineVersion == 0) {
                 NSLog(@"🙂获取到的设备在线版本为>>>0");
                 return ;
             }
             else
             {
              [self saveData:str withRequestType:requestType];
             }
         } else {
             return;
         }
     }   failed:^(MKNetworkOperation *op, NSError *err)
     {
         //             SHOWMBProgressHUD(nil, err.localizedDescription, nil, NO, 2);
     }];
    
    [self.requestHelper submit:hr];
}

- (void)userInfoTest:(NSString *)link dict:(NSDictionary *)dict success:(NSObjectSimpleBlock)success
                fail:(NSObjectSimpleBlock)fail {
    [self.requestHelper emptyCache];
    HttpRequest *op = [self.requestHelper operationWithPath:link
                                                     params:dict
                                                 httpMethod:@"POST"];
    
    NSString *fullPath = [[XYSandbox libCachePath] stringByAppendingPathComponent:@"currentImages.jpg"];
    if (fullPath) {
        [op addFile:fullPath forKey:@"image"];
    }
    
    [op succeed:^(MKNetworkOperation *op) {
        NSDictionary *dic = op.responseString.JSONValue;
        if (success) {
            success(dic);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:op];
    op.shouldContinueWithInvalidCertificate = YES;
}

- (void)saveData:(NSString *)string withRequestType:(FileModelEntityRequest)requestType {
    switch (requestType) {
        case FileModelEntityRequestFirmware: {
            _wareInfo = [string toModel:NSClassFromString(@"WareInfoModel") forKey:@"data"];
            [self isNeedDownloadWareZip];
            break;
        }
            
        default:
            break;
    }
}

- (void)downFirmwareFile {
    dispatch_queue_t queue = dispatch_get_global_queue(
                                                       DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSURL *url     = [NSURL URLWithString:_wareInfo.download_url];
        NSError *error = nil;
        // 2
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
        if (!error) {
            NSArray *paths    = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *path    = [paths objectAtIndex:0];
            NSString *zipPath = [path stringByAppendingPathComponent:@"zipfile.zip"];
            BOOL ok           = [data writeToFile:zipPath options:0 error:&error];
            if (ok) {
                KK_ShareData.isDown                                  = YES;
                [FileModelEntity sharedInstance].wareInfo.isDownload = YES;
                [DownloadEntity sharedInstance].filePath             = zipPath;
                NSLog(@"🙂固件文件下载成功>>>");
                _lastAdv      = KK_BLEModel.bleAdvID;
                _lastDeviceId = KK_BLEModel.deviceID;
                _lastCustoms = KK_BLEModel.bleCustomerID;
                if (self.block) {
                    self.block();
                }
            } else {
                NSLog(@"固件文件下载失败>>>");
            }
            if (!error) {
                // TODO: Unzip
            } else {
                NSLog(@"Error saving file %@", error);
            }
        } else {
            NSLog(@"Error downloading zip file: %@", error);
        }
    });
}

- (void)isNeedDownloadWareZip {
    if (_wareInfo) {
        KK_BLEModel.bleOnlineVersion = _wareInfo.version.integerValue;
        NSLog(@"设备固件在线版本 >>%d 当前固件版本>>>%d", KK_BLEModel.bleOnlineVersion, KK_BLEModel.bleVersion);
        if (KK_BLEModel.bleOnlineVersion == 0 && _wareInfo.download_url.length == 0) {
            return;
        }
        if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion) {
            // 是否已经下载并进行了文件缓存.
            if (_wareInfo.isDownload) {
                //                NSString *fileName = [[_wareInfo.file componentsSeparatedByString:@"/"] lastObject];
                //                [DownloadEntity sharedInstance].filePath = [NSString stringWithFormat:@"%@/%@", [XYSandbox libCachePath], fileName];
            } else {
                // 没有下载就开始下载.
                if (_wareInfo.download_url.length > 0) {
//            [[DownloadEntity sharedInstance] downloadFileWithWebsite:_wareInfo.download_url
//                                                     withRequestType:DownloadEntityRequestFirmware];
                    [self downFirmwareFile];
                } else {
                    SHOWMBProgressHUD(nil, SN_Text(@"没有下载地址"), nil, NO, 1.0);
                }
            }
        }
    }
}

- (void)requestSuccessWithString:(NSString *)string withRequestType:(FileModelEntityRequest)requestType {
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData       *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic      = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    return dic;
}

/*********************************************同步历史数据*****************************************************/

// 同步历史数据
- (void)MKGET:(NSString *)link params:(NSDictionary *)dict
      success:(NSObjectSimpleBlock)success
         fail:(NSObjectSimpleBlock)fail {
    [self.requestHelper emptyCache];
    
    HttpRequest *hr = [self.requestHelper get:link params:dict];
    [hr succeed:^(MKNetworkOperation *op) {
        NSString *respon = op.responseString;
        if (success) {
            success(respon);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:hr];
}

// 从服务器同步数据
- (void)MKPOST:(NSString *)link params:(NSDictionary *)dict
       success:(NSObjectSimpleBlock)success
          fail:(NSObjectSimpleBlock)fail {
    [self.requestHelper emptyCache];
    
    HttpRequest *hr = [self.requestHelper post:link params:dict];
    [hr succeed:^(MKNetworkOperation *op) {
        NSString *respon = op.responseString;
        if (success) {
            success(respon);
        }
    } failed:^(MKNetworkOperation *op, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    
    [self.requestHelper submit:hr];
    //    hr.shouldContinueWithInvalidCertificate = YES;
}

// 同步历史数据
- (void)MKNetGET:(NSString *)link params:(NSDictionary *)dict
         success:(NSObjectSimpleBlock)success
            fail:(NSObjectSimpleBlock)fail {
    MKNetworkEngine    *engine = [[MKNetworkEngine alloc] initWithHostName:@"api.core.iwear88.com" customHeaderFields:nil];
    MKNetworkOperation *op     = [engine operationWithPath:link params:dict httpMethod:@"GET" ssl:NO];
    
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSString *respon = operation.responseString;
        NSDictionary *dic = [self dictionaryWithJsonString:respon];
        if ([dic[@"ret"] integerValue]==401) {
//            SHOWMBProgressHUD(nil, SN_Text(dic[@"message"]), nil, NO, 2.0);
//            [kK_App enterLoginVc];
            return ;
        }
        if (success) {
            success(dic);
        }
    } errorHandler:^(MKNetworkOperation *errorOp, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    [engine enqueueOperation:op];
    //
    //    [self.requestHelper emptyCache];
    //    HttpRequest *hr = [self.requestHelper get:link params:dict];
    //    [hr succeed:^(MKNetworkOperation *op) {
    //        NSString *respon = op.responseString;
    //        NSDictionary *dic = [self dictionaryWithJsonString:respon];
    //        if (success) {
    //            success(dic);
    //        }
    //    } failed:^(MKNetworkOperation *op, NSError *err) {
    //        if (fail) {
    //            fail(nil);
    //        }
    //    }];
    //    [self.requestHelper submit:hr];
}

// 从服务器同步数据
- (void)MKNetPOST:(NSString *)link params:(NSDictionary *)dict
          success:(NSObjectSimpleBlock)success
             fail:(NSObjectSimpleBlock)fail {
    MKNetworkEngine    *engine = [[MKNetworkEngine alloc] initWithHostName:@"api.core.iwear88.com" customHeaderFields:nil];
    MKNetworkOperation *op     = [engine operationWithPath:link params:dict httpMethod:@"POST"];
    
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSString *respon = operation.responseString;
        NSDictionary *dic = [self dictionaryWithJsonString:respon];
        if ([dic[@"ret"] integerValue]==401) {
//            SHOWMBProgressHUD(nil, SN_Text(dic[@"message"]), nil, NO, 2.0);
//            [kK_App enterLoginVc];
            return ;
        }
        if (success) {
            success(dic);
        }
    } errorHandler:^(MKNetworkOperation *errorOp, NSError *err) {
        if (fail) {
            fail(nil);
        }
    }];
    [engine enqueueOperation:op];
    
    //        [self.requestHelper emptyCache];
    //        HttpRequest *hr = [self.requestHelper post:link params:dict];
    //        [hr succeed:^(MKNetworkOperation *op) {
    //            NSString *respon = op.responseString;
    //            NSDictionary *dic = [self dictionaryWithJsonString:respon];
    //            if (success) {
    //                success(dic);
    //            }
    //        } failed:^(MKNetworkOperation *op, NSError *err) {
    //            if (fail) {
    //                fail(nil);
    //            }
    //        }];
    //        [self.requestHelper submit:hr];
    //    hr.shouldContinueWithInvalidCertificate = YES;
}

//  同步网络数据
- (void)syncDataFromServer {
    NSInteger localSportDays = [SportModel localSportDays];
    
    NSLog(@"SN_USER.sport_days>>>%d   localSportDays>>%d", SN_USER.sport_days, localSportDays);
    
    if (SN_USER.sport_days > 0 && (SN_USER.sport_days > localSportDays)) {
        [self downloadSport];
        [self downloadSleep];
        [self downloadExam:@"1"];
        [self downloadExam:@"2"];
        [self downloadExam:@"3"];
    }
}

// 运动
- (void)downloadSport {
    if (SN_USER.create_time && SN_USER.access_token) {
        NSString *beginDate = [SN_USER.create_time componentsSeparatedByString:@" "][0];
        NSString *endDate   = [[NSDate date] dateToDayString];
        
        NSDictionary *args = @{@"access_token" : SN_USER.access_token,
                               @"beginDate" : beginDate,
                               @"endDate" : endDate};
        
        [self MKGET:@"/sport/dates" params:args success:^(id object) {
            // object 为服务器运动数据对象数组
            NSString *respon = (NSString *)object;
            if ([respon rangeOfString:@"user_id"].length > 0) {
                NSArray *array = [respon toModels:SportModel.class forKey:@"data"];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    for (SportModel *model in array) {
                        [model saveToDBByDownload];
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (self.syncEnd) {
                            self.syncEnd(nil);
                        }
                    });
                });
            }
        } fail:^(id object) {
        }];
    }
}

// 睡眠
- (void)downloadSleep {
    if (SN_USER.create_time && SN_USER.access_token) {
        NSString *beginDate = [SN_USER.create_time componentsSeparatedByString:@" "][0];
        NSString *endDate   = [[NSDate date] dateToDayString];
        
        NSDictionary *args = @{@"access_token" : SN_USER.access_token,
                               @"beginDate" : beginDate,
                               @"endDate" : endDate};
        
        [self MKGET:@"/sleep/dates" params:args success:^(id object) {
            // object 为服务器睡眠数据对象数组
            NSString *respon = (NSString *)object;
            if ([respon rangeOfString:@"user_id"].length > 0) {
                NSArray *array = [respon toModels:SleepModel.class forKey:@"data"];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    for (SleepModel *model in array) {
                        [model saveToDBByDownload];
                    }
                });
            }
        } fail:^(id object) {
        }];
    }
}

//  体检
- (void)downloadExam:(NSString *)type {
    if (SN_USER.create_time && SN_USER.access_token) {
        NSString *beginDate = [SN_USER.create_time componentsSeparatedByString:@" "][0];
        NSString *endDate   = [[NSDate date] dateToDayString];
        
        NSDictionary *args = @{@"access_token" : SN_USER.access_token,
                               @"beginDate" : beginDate,
                               @"endDate" : endDate,
                               @"type" : type};
        
        [self MKGET:@"/examination/dates2" params:args success:^(id object) {
            // object 为服务器体检数据对象数组
            NSString *respon = (NSString *)object;
            if ([respon rangeOfString:@"user_id"].length > 0) {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    if (type.integerValue == 1) {
                        NSArray *array = [respon toModels:OxModel.class forKey:@"data"];
                        for (OxModel *model in array) {
                            [model saveToDBByDownload];
                        }
                    } else if (type.integerValue == 2) {
                        NSArray *array = [respon toModels:HeartModel.class forKey:@"data"];
                        for (HeartModel *model in array) {
                            [model saveToDBByDownload];
                        }
                    } else if (type.integerValue == 3) {
                        NSArray *array = [respon toModels:BpModel.class forKey:@"data"];
                        for (BpModel *model in array) {
                            [model saveToDBByDownload];
                        }
                    }
                });
            }
        } fail:^(id object) {
        }];
    }
}

@end
